//
//  RVCommonListController.swift
//  AirTravel
//
//  Created by 许必成 on 2021/11/15.
//

import UIKit
import HandyJSON
enum RVInfoType {
    case passenger
    case contacter
}

class RVCommonListController: UIViewController {

    var type: RVInfoType
    
    
    var dataSource: [RVMyCommenInfoList] = []
    
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var addBtn: UIButton!
    
    init(type: RVInfoType) {
        self.type = type
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        confUI()
        getData()
    }
    
    func confUI(){
        
        switch type {
        case .contacter:
            addBtn.setTitle("新增联系人", for: .normal)
            tableView.rowHeight = 65
        case .passenger:
            addBtn.setTitle("新增出行人", for: .normal)
            tableView.rowHeight = 83
        }
        tableView.register(UINib(nibName: "RVInfoListCell", bundle: nil), forCellReuseIdentifier: "info_list")
    }

    @IBAction func clickAddBtn(_ sender: UIButton) {
        
        navigationController?.pushViewController(RVNewddressController(), animated: true)
        
        
    }
    
    func getData(){
        YProgressHUD.show()
        NetWorkRequest(API1.getCommenInfo) { json in
            YProgressHUD.dismiss()
            guard let data = JSONDeserializer<RVMyCommenInfoData>.deserializeFrom(dict: json.dictionaryObject) else{
                return
            }
            self.dataSource = data.data
            self.tableView.reloadData()
        } failed: { msg in
            YProgressHUD.dismiss()

        } errorResult: {
            YProgressHUD.dismiss()
        }
    }

}

extension RVCommonListController: UITableViewDelegate, UITableViewDataSource{
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "info_list", for: indexPath) as! RVInfoListCell
        cell.passengerNameLabel.isHidden = true
        cell.cardNOLabel.isHidden = true
        let list = dataSource[indexPath.row]
        cell.contactNameLabel.text = list.nickname;
        
//        cell.contactNameLabel.isHidden = type == .passenger
//        cell.passengerNameLabel.isHidden = type == .contacter
//        cell.cardNOLabel.isHidden = type == .contacter
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

